package com.angel.bo.message.service.impl;

import com.angel.bo.beans.message.AngelMessage;
import com.angel.bo.common.msg.WebReturn;
import com.angel.bo.common.util.JsonUtil;
import com.angel.bo.message.service.AngelMessageService;
import com.angel.bo.message.session.SocketSessionRegistry;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;

/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description:
 * @Date: 10:02 2018/3/5 
 */
@Service
@Slf4j
public class AngelMessageServiceImpl implements AngelMessageService{


    /**消息发送工具*/
    @Autowired
    private SimpMessagingTemplate messagingTemplate;



    @Autowired
    private SocketSessionRegistry webAgentSessionRegistry;

    /**
     * @param angelMessage
     * @Author: Haibo.Mei [Haibo.Mei@ge.com]
     * @Description: 发送消息
     * @Date: 10:04 2018/3/5
     */
    @Override
    public WebReturn sendMessage(AngelMessage angelMessage) {

        List<String> receivers = angelMessage.getReceiver();
        if(receivers.size() == 0){

            //遍历所有的session
            ConcurrentMap<String, Set<String>> allSessionIds = webAgentSessionRegistry.getAllSessionIds();
            for(Map.Entry<String, Set<String>> entry : allSessionIds.entrySet()){
                Set<String> sessionIds = entry.getValue();
                for (String session : sessionIds) {
                    messagingTemplate.convertAndSendToUser(session,"/queue/receive", JsonUtil.toJson(angelMessage),createHeaders(session));
                }
            }

        }

        for (String receiver : receivers) {
            String sessionId = StringUtils.join(webAgentSessionRegistry.getSessionIds(receiver).toArray());
            log.info("发送给{},sessionId:{}",receiver,sessionId );
            if(sessionId != null){
                messagingTemplate.convertAndSendToUser(sessionId,"/queue/receive",JsonUtil.toJson(angelMessage),createHeaders(sessionId));
            }
        }

        return new WebReturn("发送成功");
    }

    private MessageHeaders createHeaders(String sessionId) {
        SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
        headerAccessor.setSessionId(sessionId);
        headerAccessor.setLeaveMutable(true);
        return headerAccessor.getMessageHeaders();
    }
}
